package com.wswy.wzcx.ui.njdb

import android.arch.lifecycle.Observer
import android.content.Context
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PagerSnapHelper
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.util.SparseIntArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.ui.adapter.SampleRecyclerViewAdapter
import com.che.libcommon.utils.ToastUtils
import com.che.libcommon.widget.viewpager.RecyclingPagerAdapter
import com.wswy.wzcx.R
import com.wswy.wzcx.model.car.CarStatus
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.UserDataProvider
import com.wswy.wzcx.module.base.*
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.car.remind.RemindActivity
import com.wswy.wzcx.utils.UiUtils
import kotlinx.android.synthetic.main.fragment_njdb_service.*
import kotlinx.android.synthetic.main.layout_tab_nj_yuyue.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
import timber.log.Timber
import kotlin.math.max

class InspectionServiceFragment : CBaseFragment() {

    companion object{
        @JvmStatic
        fun newInstance(bundle: Bundle?):InspectionServiceFragment{
            return InspectionServiceFragment().apply {
                arguments = bundle
            }
        }
    }


    override fun getContentLayoutId(): Int {
        return R.layout.fragment_njdb_service
    }

    override fun getFragmentTitle(): String {
        return "年检代办"
    }


    private lateinit var njServiceViewModel: NjServiceViewModel
    private lateinit var  adapter : CarAdapter

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        recycler_view.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)

        recycler_view.addMargin(SizeUtils.dp2px(12f),SizeUtils.dp2px(12f))

        indicators.setDefaultColor(getColor(R.color.color_gary))
        indicators.setSelectedColor(getColor(R.color.color_orange))

        njServiceViewModel = provideViewModel(NjServiceViewModel::class.java)
        njServiceViewModel.onCreate()

        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(recycler_view)

        recycler_view.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if (newState == RecyclerView.SCROLL_STATE_IDLE){

                    val pos = pagerSnapHelper.getSnapPosition(recyclerView)
                    indicators.selectedPosition = pos
                    Timber.e("pos --- $pos    ${adapter.getItemData(pos)}")

                    adapter.getItemData(pos)?.let {
                        onShowCar(it)
                    }

                }

            }
        })

        if(njServiceViewModel.hasLogin()){
            //已登录  有车

            if (UserDataProvider.get().hasCar()){

                nest_scrollview.isFillViewport = true
                showTips()
                showCars()
                tv_apply.onClick(::clickApply)

            }else{
                ToastUtils.showText("请先添加车辆")

                finish()
            }


        }else{

            //未登录

            njServiceViewModel.gotoLogin(requireContext())

            finish()
        }



    }

    private fun clickApply(view: View){
        (view.getTag(R.id.item_data) as? NjVoModel)?.let {model ->

            when(model.status){

                CarStatus.NJ_NONE -> {
                    //需要补充资料
                    RemindActivity.startInspection(view.context,model.userCarInfo)
                }

                else -> {
                    ModuleActivity.getTargetIntent(view.context,NjdbOrderFragment.TAG,Bundle().apply {
                        putParcelable(Constants.EXTRA_DATA,model.userCarInfo)
                    }).let {
                        startActivity(it)
                    }
                }

            }
        }
    }

    private fun onShowCar(njVoModel: NjVoModel){
        //显示当前状态
        tv_apply.setTag(R.id.item_data,njVoModel)

        //底部按钮
        when(njVoModel.status){
            CarStatus.NJ_NONE -> {
                tv_apply.text = "补充资料"
                tv_apply.isEnabled = true
            }
            CarStatus.NJ_NORMAL -> {
                tv_apply.text = "无需办理"
                tv_apply.isEnabled =false
            }
            CarStatus.NJ_CAN_RESERVATION -> {
                tv_apply.text = getString(R.string.immediately_reservation)
                tv_apply.isEnabled =true
            }
            else -> {
                tv_apply.text = getString(R.string.immediately_apply)
                tv_apply.isEnabled =true
            }
        }

        //底部切换
        when(njVoModel.status){
            CarStatus.NJ_CAN_RESERVATION -> {
                showYuyue()
            }
            else -> {
                showTips()
            }
        }
    }


    private fun showCars(){
        adapter = CarAdapter()

        val defUserCarId = arguments?.getParcelable<UserCarInfo?>(Constants.EXTRA_USER_CAR_INFO)?.id?:0

        adapter.clickCallback = View.OnClickListener {
            if (it?.id == R.id.img_edit){

                //编辑
                (it.getTag(R.id.item_data) as? NjVoModel)?.let {model ->
                    RemindActivity.startInspection(it.context,model.userCarInfo,0,true)
                }

            }else{
                clickApply(it)
            }

        }

        recycler_view.adapter = adapter

        njServiceViewModel.getUserCarsLiveData().observe(this, Observer {

            it?.runCatching {

                if (isOk()){

                    data?.map { NjVoModel(it) }?.let {
                        indicators.useDefaultColors(it.size)


                        adapter.setNewData(it)
                        adapter.notifyDataSetChanged()


                        var defPos = 0
                        if (defUserCarId > 0){
                            defPos = it.indexOfFirst { it.userCarInfo.id == defUserCarId }
                        }
                        if (defPos <=0){
                            defPos = 0
                        }else{
                            //有默认的车辆，滑动到指定位置
                            recycler_view.scrollToPosition(defPos)
                        }
                        indicators.selectedPosition = defPos
                        onShowCar(it[defPos])

                        //indicators.selectedPosition = 0
                        //onShowCar(it.first())


                    }
                }
            }

        })

        //车辆更新

        njServiceViewModel.getCarUpdateLiveData().observe(this, Observer {


            it?.runCatching {

                val idx = adapter.datas?.indexOfFirst { it?.userCarInfo?.id == id }?:-1

                if (idx != -1){
                    //更新数据
                    val newData  = NjVoModel(this)
                    adapter.datas?.set(idx,newData)

                    adapter.notifyItemChanged(idx)

                    if (indicators.selectedPosition == idx){
                        //刷新
                        onShowCar(newData)
                    }

                }


            }

        })


    }

    private fun showYuyue(){
        //显示预约提醒

        fl_container_reservation.visible()
        fl_container.gone()

        if (img_nj_yy_pos_1.drawable == null){
            img_nj_yy_pos_1.setImageDrawable(NumDrawable("1"))
        }
        if(img_nj_yy_pos_2.drawable == null){
            img_nj_yy_pos_2.setImageDrawable(NumDrawable("2"))
        }
        if (img_nj_yy_pos_3.drawable == null){
            img_nj_yy_pos_3.setImageDrawable(NumDrawable("3"))
        }


    }

    private lateinit var titleNavigator : CommonNavigator


    private fun showTips(){
        //显示年检办理流程提醒

        if (this::titleNavigator.isInitialized){
            fl_container_reservation.gone()
            fl_container.visible()
            return
        }


        val context = requireContext()
        titleNavigator = CommonNavigator(context).apply {
            isAdjustMode = true
        }

        val datas = arrayListOf<String>("6年免检","代办流程","所需资料","常见问题")

        titleNavigator.adapter = object : CommonNavigatorAdapter() {

            override fun getCount(): Int {
                return datas.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val pagerTitleView = SimplePagerTitleView(context)
                pagerTitleView.text = datas[index]
                pagerTitleView.textSize = 14f
                pagerTitleView.selectedColor = ContextCompat.getColor(context,R.color.textColorPrimary)
                pagerTitleView.normalColor = ContextCompat.getColor(context,R.color.textColorPrimary_70)
                pagerTitleView.setOnClickListener { viewPager.currentItem = index }
                return pagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator? = LinePagerIndicator(context).apply {
                setColors(getColor(R.color.color_orange))
                lineWidth = SizeUtils.dp2px(28f).toFloat()
                lineHeight = SizeUtils.dp2px(4f).toFloat()
                roundRadius = SizeUtils.dp2px(3f).toFloat()
                mode = LinePagerIndicator.MODE_EXACTLY
            }


        }

        magic_indicator.navigator = titleNavigator
        viewPager.clearOnPageChangeListeners()
        ViewPagerHelper.bind(magic_indicator, viewPager)

        viewPager.pageMargin = SizeUtils.dp2px(12f)

        viewPager.offscreenPageLimit  = 1

        viewPager.adapter = object : RecyclingPagerAdapter(){

            private val layouts = arrayOf(R.layout.layout_tab_nj_1,R.layout.layout_tab_nj_2,R.layout.layout_tab_nj_3,R.layout.layout_tab_nj_4)

            private val firstH = SparseIntArray().apply {

                put(0,SizeUtils.dp2px(810f))
//                put(0,1601)
//                put(1,SizeUtils.dp2px(517f))
//                put(2,SizeUtils.dp2px(1008f))
                //put(3,SizeUtils.dp2px(448f))

            }

            override fun getView(position: Int, convertView: View?, container: ViewGroup): View {
                layouts.getOrNull(position)?.let {
                    return LayoutInflater.from(container.context).inflate(it,container,false).also {
                        process(it,position)
                    }
                }?:kotlin.run {
                    return FrameLayout(container.context)
                }
            }

            private fun process(itemView: View,position: Int){

                when(position){
                    0 -> {
                        setTitleNum(itemView,R.id.tv_title_1,1)
                        setTitleNum(itemView,R.id.tv_title_2,2)
                        setTitleNum(itemView,R.id.tv_title_3,3)

                    }
                    1 -> {
                        //
                    }
                    2 -> {
                        setTitleNum(itemView,R.id.tv_title_1,1)
                        setTitleNum(itemView,R.id.tv_title_2,2)
                        setTitleNum(itemView,R.id.tv_title_3,3)
                    }
                    3 -> {
                        setQuestion(itemView,itemView.findViewById(R.id.recycler_view_question))
                    }
                }




//                itemView.layoutParams?.let {
//
//
//                    val ch = firstH.get(position,-1)
//                    val h = if (ch < 0 && position != 3) {
//                        itemView.forceLayout()
//                        itemView.measure(0,View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE shr 2, View.MeasureSpec.AT_MOST))
//                        max(itemView.height,itemView.measuredHeight)
//                    } else ch
//
//                    if (position == 3){
//                        //特殊处理
//                    }
//
//                    Timber.e("----$position   $h ")
//
//                    if (h > 0 && it.height != h){
//                        //测量出宽高了
//                        firstH.put(position,h)
//                        it.height = h
//                        itemView.layoutParams = it
//                    }
//
//                }
//


            }

            private fun setTitleNum(itemView: View, @IdRes resId:Int, num:Int){
                itemView.findViewById<TextView>(resId)?.setCompoundDrawables(NumDrawable(num.toString()), null, null, null)
            }

            private fun setQuestion(itemView: View,recyclerView: RecyclerView){
                recyclerView.layoutManager = LinearLayoutManager(recyclerView.context)
                recyclerView.isNestedScrollingEnabled = true

                val adapter = QA4Adapter()

                recyclerView.adapter = adapter

                adapter.setNewData(arrayListOf(QA("6年年检办理周期","用户上传行驶证、保险单副本、车主身份证资料通过审核后，我们将在3个工作日内办理完毕，并安排邮寄年检标志;如因用户所提供资料不合格耽误办理，办理周期将按收到用户合格资料后3个工作日内办理完毕"),
                        QA("年检可以提前办理吗？","6年年检可提前3个月办理，以行驶证副本上所显示的年审有效期为准，包含当月，仅精确至月份不限制具体日期，举例如年审有限期为2017年9月，则最早可提前至7月份办理，建议您在年审有效期到期前办理年审，不要逾期未审。"),
                        QA("预期未年检如何处理？","逾期未年检车辆属于 脱审，不符合交通法规是不支持上路开车的，大部分地区逾期年检需要扣分处罚后再办理，部分地区逾期一定周期内不予处罚可直接办理。"),
                        QA("年年检需要哪些资料？","1、保险单副本扫描件(保单需要在有效期内)\n2、车主身份证扫描件(正反两面)\n3、车辆行驶证扫描件(正副两面)\n4、机动车业务委托书(仅公司车需提供)"),
                        QA("年检办理条件有哪些？","1、使用性质:非运营\n2、核定载人数: 6人及以下\n3、行驶证注明的9种车型:微型轿车、小型轿车、中型轿车、大型轿车、小型普通客车、小型越野客车、小型专用客车、微型普通客车、微型越野客车\n4、注册登记日期未超过6年\n5、年检期间未发生过致人伤亡事故的车辆")))
                adapter.notifyDataSetChanged()

            }

            override fun getCount(): Int {
                return datas.size
            }

            override fun setPrimaryItem(container: ViewGroup, position: Int, obj: Any) {
                super.setPrimaryItem(container, position, obj)

//                if (obj is View){
//                    UiUtils.addOnPreDrawListener(obj){
//                        Timber.e(" OnPreDraw -----$position  ::==  ${it.height}   ${it.measuredHeight}")
//                    }
//
//                    UiUtils.addOnGlobalLayoutListener(obj){
//
//                        it.measure(0, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
//
//                        Timber.e("OnGlobalLayout -----$position  ::==  ${it.height}   ${it.measuredHeight}")
//                    }
//                }


                container.layoutParams?.let {

                    if (obj is View ){

//                        if (position == 0){
//                            obj.measure(0,View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
//                            //max(obj.height,obj.measuredHeight)
//
//                            Timber.e("hhh   h:${ obj.height }   h:pb:${ obj.measuredHeight+obj.paddingBottom }    mh:${obj.measuredHeight}    fh:${firstH.get(position,0)}")
//                        }
                         //firstH.indexOfKey(position) < 0 &&


                        val ch = firstH.get(position,-1)
                        val h = if (ch < 0 && position != 3) {

                            obj.measure(0,0)
                            obj.measuredHeight
                        } else if (position == 3){
                            0
                        }else {

                            obj.measure(0,0)

                            //Timber.e("----else  $position  ${obj.height} ${obj.measuredHeight}")

                            max(ch,obj.measuredHeight)
                        }

                        if (position == 3){
                            //特殊处理
                        }

                        //Timber.e("----$position  ch:$ch  h:$h ")

                        if (h > 0 && it.height != h){

                            //测量出宽高了
                            firstH.put(position,h)

                            it.height = h
                            container.layoutParams = it

                            obj.requestLayout()
                        }

                    }

                }

            }

        }

    }


    private class QA4Adapter : SampleRecyclerViewAdapter<QA,QAViewHolder>(){

        private val qaExpand = hashSetOf<Int>()

        init {

            setOnItemClickListener { _, position, t ->

                if (qaExpand.contains(position)){
                    //已经展开
                    qaExpand.remove(position)
                }else{
                    qaExpand.add(position)
                }
                notifyItemChanged(position)

            }

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QAViewHolder {
            return QAViewHolder(loadLayout(parent,R.layout.layout_item_njdb_tip4_qa))
        }

        override fun onBindViewHolder(holder: QAViewHolder, position: Int, data: QA?) {
            holder.setNum(position+1)
            holder.tvTitle.text = data?.title
            holder.tvContext.text = data?.answer
            if (qaExpand.contains(position)){
                holder.expand()
            }else{
                holder.close()
            }
        }

    }

    private class CarAdapter : SampleRecyclerViewAdapter<NjVoModel?,UserCarViewHolder>(){

        var clickCallback : View.OnClickListener? = null

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserCarViewHolder {
            return UserCarViewHolder(loadLayout(parent,R.layout.layout_item_njdb_car))
        }

        override fun onBindViewHolder(holder: UserCarViewHolder, position: Int, data: NjVoModel?) {

            data?.let {
                holder.bind(it)
                holder.tvBtn.setTag(R.id.item_data,it)
                holder.tvBtn.setOnClickListener(clickCallback)
                holder.imgEdit.setTag(R.id.item_data,it)
                holder.imgEdit.setOnClickListener(clickCallback)
            }

        }

    }

    //车辆信息
    private class UserCarViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){


        private val tvCarNo = itemView.findViewById<TextView>(R.id.tv_car_no)
        private val tvNjHint  = itemView.findViewById<TextView>(R.id.tv_nj_hint)
        val tvBtn = itemView.findViewById<TextView>(R.id.tv_nj_btn)
        val imgEdit = itemView.findViewById<ImageView>(R.id.img_edit)


        fun bind(njVoModel: NjVoModel){
            tvCarNo.text = njVoModel.userCarInfo.carNo

            var text:CharSequence?=null
            var btnText:CharSequence?=null

            when(njVoModel.status){

                CarStatus.NJ_NONE -> {
                    text = "请补充车辆信息，查看年检状态"
                    btnText = "补充资料"
                }
                CarStatus.NJ_NORMAL -> {

                    text = SpannableStringBuilder().apply {
                        append("距可办理还有")
                        append(SpannableString("${njVoModel.days}").apply {
                            setSpan(ForegroundColorSpan(ContextCompat.getColor(itemView.context,R.color.textColorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            setSpan(RelativeSizeSpan(20f/14f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                        })
                        append("天")
                    }
                    btnText = "无需办理"
                }

                CarStatus.NJ_CAN_RESERVATION -> {

                    text = SpannableStringBuilder().apply {
                        append("距可办理还有")
                        append(SpannableString("${njVoModel.days}").apply {
                            setSpan(ForegroundColorSpan(ContextCompat.getColor(itemView.context,R.color.textColorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            setSpan(RelativeSizeSpan(20f/14f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                        })
                        append("天")
                    }
                    btnText = tvNjHint.context.getString(R.string.immediately_reservation)

                }

                CarStatus.NJ_CAN_APPLY -> {
                    text = SpannableStringBuilder().apply {
                        append("距到期还有")
                        append(SpannableString("${njVoModel.days}").apply {
                            setSpan(ForegroundColorSpan(ContextCompat.getColor(itemView.context,R.color.textColorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            setSpan(RelativeSizeSpan(20f/14f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                        })
                        append("天")
                    }
                    btnText = tvNjHint.context.getString(R.string.immediately_apply)
                }

                CarStatus.NJ_OVERDUE -> {
                    text = SpannableStringBuilder().apply {
                        append("年检已逾期")
                        append(SpannableString("${njVoModel.days}").apply {
                            setSpan(ForegroundColorSpan(ContextCompat.getColor(itemView.context,R.color.car_no_big)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                            setSpan(RelativeSizeSpan(20f/14f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                        })
                        append("天")
                    }
                    btnText = tvNjHint.context.getString(R.string.immediately_apply)
                }

            }
            tvNjHint.text = text
            tvBtn.text = btnText
            tvBtn.isEnabled = njVoModel.status != CarStatus.NJ_NORMAL


//            njVoModel.userCarInfo.carExtendInfo?.inspection?.run {
//
//                tvNjHint.text = SpannableStringBuilder().apply {
//                    append("距离年检还有")
//                    append(SpannableString("$remainDay").apply {
//                        setSpan(ForegroundColorSpan(ContextCompat.getColor(itemView.context,R.color.textColorPrimary)),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                        setSpan(RelativeSizeSpan(20f/14f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
//                    })
//                    append("天")
//                }
//                tvBtn.text = "立即办理"
//
//            }?:kotlin.run {
//
//                tvNjHint.text = "请补充车辆信息，查看年检状态"
//                tvBtn.text = "补充资料"
//            }

        }

    }


    //常见问题
    private data class QA(val title:String,val answer:String)
    private class QAViewHolder (itemView: View):RecyclerView.ViewHolder(itemView){

        val tvTitle = itemView.findViewById<TextView>(R.id.tv_title)
        val tvContext = itemView.findViewById<TextView>(R.id.tv_content)
        val imgArrow = itemView.findViewById<View>(R.id.img_arrow)


        fun setNum(position: Int){
            tvTitle.setCompoundDrawables(NumDrawable(position.toString()),null,null,null)
        }

        fun expand(){
            tvTitle.setTextColor(ContextCompat.getColor(tvTitle.context,R.color.colorPrimary))
            tvContext.visible()
            imgArrow.rotation = 180f
        }

        fun close(){
            tvTitle.setTextColor(ContextCompat.getColor(tvTitle.context,R.color.textColorPrimary))
            tvContext.gone()
            imgArrow.rotation = 0f
        }

    }

}